package cn.moukou.tongji.ihealth.doctor.service;

import cn.moukou.tongji.ihealth.doctor.dao.PatientReserveMapper;
import cn.moukou.tongji.ihealth.doctor.pojo.PatientReserve;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PatientReserveService {

    @Autowired
    PatientReserveMapper reserveMapper;

    @Autowired
    RedissonClient redissonClient;


    public List<PatientReserve> getFreeReservesByDate(Date date) {
        QueryWrapper<PatientReserve> wrapper = new QueryWrapper<>();
        wrapper
                .eq("date", date)
                .eq("did", "")
                .select("id", "pid", "patient_name", "state");
        return reserveMapper.selectList(wrapper);
    }

    public List<PatientReserve> getMyReservesByDate(Date date, String did) {
        Map<String, Object> map = new HashMap<>();
        map.put("date", date);
        map.put("did", did);
        return reserveMapper.selectByMap(map);
    }

    public PatientReserve getOne(Long id) {
        return reserveMapper.selectById(id);
    }

    public int receiveReserve(Long id, String did) {

        RLock lock = redissonClient.getLock("reserveLock");
        lock.lock();

        PatientReserve patientReserve = reserveMapper.selectById(id);
        if(patientReserve.getState()==0) {
            patientReserve.setState(1);
            patientReserve.setId(id);
            patientReserve.setDid(did);
            lock.unlock();
            return reserveMapper.updateById(patientReserve);
        } else {
            lock.unlock();
            return -1;
        }
    }

    public int cancelReserve(Long id) {
        PatientReserve patientReserve = reserveMapper.selectById(id);
        if(patientReserve.getState()==2) {
            return -1;
        }
        patientReserve.setDid("");
        patientReserve.setState(0);
        return reserveMapper.updateById(patientReserve);
    }

}
